package com.happy.config.shiro;

import com.alibaba.fastjson.JSONObject;
import com.happy.util.constants.ErrorEnum;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.Charset;

/**
 * @Auther: lifeng
 * @Date: 2018/6/26 16:23
 * @Description: 对没有登录的请求进行拦截, 全部返回json信息. 覆盖掉shiro原本的跳转login.jsp的拦截方式
 */
public class AjaxPermissionsAuthorizationFilter extends FormAuthenticationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("returnCode",ErrorEnum.E_20011.getErrorCode());
        jsonObject.put("returnMsg",ErrorEnum.E_20011.getErrorMsg());

        try {
            HttpServletResponse res = (HttpServletResponse) response;
            try(PrintWriter printWriter  = res.getWriter()){
                res.setCharacterEncoding("UTF-8");
                res.setContentType("application/json");
                printWriter.println(jsonObject);
            }catch (Exception e){

            }
        }catch (Exception e){

        }
        return false;
    }

    @Bean
    public FilterRegistrationBean registration(AjaxPermissionsAuthorizationFilter ajaxPermissionsAuthorizationFilter){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(ajaxPermissionsAuthorizationFilter);
        return registrationBean;
    }
}
